package com.meixiang.dialog;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.meixiang.R;
import com.meixiang.activity.WebviewActivity;
import com.meixiang.activity.account.myfund.FundDetialViewActivity;
import com.meixiang.activity.account.myfund.FundListMainActivity;
import com.meixiang.activity.account.myfund.MyFundActivity;
import com.meixiang.adapter.myFundAdapter.FundSearchDataAdapter;
import com.meixiang.entity.fund.FundNewSerchResult;
import com.meixiang.global.Config;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.recyclerview.OnItemClick;
import com.meixiang.tool.Tool;
import com.meixiang.util.AbJsonUtil;
import com.meixiang.view.ClearEditText;
import com.meixiang.view.flowlayout.CustomFlowAdapter;
import com.meixiang.view.flowlayout.CustomFlowLayout;
import com.meixiang.view.swipetoloadlayout.base.OnLoadMoreListener;
import com.meixiang.view.swipetoloadlayout.base.SwipeToLoadLayout;

import org.json.JSONObject;

import java.util.Arrays;
import java.util.List;

/**
 * Created by Administrator on 2016/5/18.
 * 弹出 popupWindow 层
 */
public class FundListSearchPopup extends PopupWindow implements View.OnClickListener, OnLoadMoreListener {

    private FundSearchDataAdapter mSearchAdapter;
    private RecyclerView screen_swipe_target; //数据列表
    private SwipeToLoadLayout mLayout;
    private ClearEditText edt_search;
    private CustomFlowLayout tag_flow;
    private TextView search_result_number;
    private TextView cancalText;
    private View parentView; //父类属兔
    private Context mContext;
    private Activity activity;
    private String[] searchData;
    private LinearLayout ll_hot_word_layout, ll_search_result_layout; //热门搜索、搜索结果layout
    private List<FundNewSerchResult.FundInfoEntity> searchResult;
    private int page = 1;
    private int pageSize = 10;
    private boolean isLoadMore = false;

    public FundListSearchPopup(Context context, View parentView, Activity activity) {
        this.parentView = parentView;
        this.mContext = context;
        this.activity = activity;
        initView();
        initData();
    }

    private void initData() {
        this.setContentView(parentView);
        this.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        this.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        this.setFocusable(true);
        this.setOutsideTouchable(true);
        this.setBackgroundDrawable(new ColorDrawable(0));
        initSearchData();
        getHotWord();
        this.setAnimationStyle(R.style.hold_search_anim_style);
    }

    /**
     * 初始化搜索数据
     */
    private void initSearchData() {
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        screen_swipe_target.setLayoutManager(mLayoutManager);
        screen_swipe_target.setItemAnimator(new DefaultItemAnimator());
        mSearchAdapter = new FundSearchDataAdapter(mContext);
        screen_swipe_target.setAdapter(mSearchAdapter);
        ll_search_result_layout.setVisibility(View.VISIBLE);
        mLayout.setOnLoadMoreListener(this);
        mLayout.setRefreshEnabled(false);
        mSearchAdapter.setOnItemClickListener(new OnItemClick() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(mContext, WebviewActivity.class);
                intent.putExtra("url", Config.FUND_INFO_NEW + "?fund_id=" + searchResult.get(position).getFund_id());
                intent.putExtra("title", searchResult.get(position).getFund_name());
                mContext.startActivity(intent);
            }
        });
    }

    /**
     * 获取网络热搜词
     */
    private void getHotWord() {
        HttpUtils.post(Config.FUND_HOT_WORD,MyFundActivity.TAG,null, new HttpCallBack(activity) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                String resutl = result.optString("hot_key").substring(
                        result.optString("hot_key").indexOf("[") + 1, result.optString("hot_key").indexOf("]"));
                searchData = resutl.replaceAll("\"", "").split(",");
                initHotWordData();
            }

            @Override
            public void onError(String code, String message) {

            }
        });
    }

    /**
     * 基金搜索结果 此方法Get请求
     */
    private void getFundNewSearch() {
        String searchUrl = Config.FUND_SEARCH + "?content=" + edt_search.getText().toString() + "&pageSize=" + String.valueOf(pageSize) + "&page=" + String.valueOf(page);
        HttpUtils.get(searchUrl, new HttpCallBack(activity, "数据获取中.....") {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                FundNewSerchResult fundNewSerchResult = AbJsonUtil.fromJson(result.optString("data"), new TypeToken<FundNewSerchResult>() {
                });
                if (fundNewSerchResult != null && fundNewSerchResult.getFund_info() != null) {
                    if (isLoadMore) {
                        searchResult.addAll(fundNewSerchResult.getFund_info());
                        mSearchAdapter.refreshData(searchResult);
                        mLayout.setLoadingMore(false);
                    } else {
                        searchResult = fundNewSerchResult.getFund_info();
                        mSearchAdapter.refreshData(searchResult);
                        search_result_number.setText("共有" + fundNewSerchResult.getFund_info().size() + "个搜索结果");
                    }
                }
            }

            @Override
            public void onError(String code, String message) {

            }
        });
    }

    private void initView() {
        screen_swipe_target = (RecyclerView) parentView.findViewById(R.id.swipe_target);
        mLayout = (SwipeToLoadLayout) parentView.findViewById(R.id.refresh);
        tag_flow = (CustomFlowLayout) parentView.findViewById(R.id.tag_flow);
        edt_search = (ClearEditText) parentView.findViewById(R.id.edt_search);
        search_result_number = (TextView) parentView.findViewById(R.id.tv_search_result_number);
        ll_hot_word_layout = (LinearLayout) parentView.findViewById(R.id.ll_hot_word_layout);
        ll_search_result_layout = (LinearLayout) parentView.findViewById(R.id.ll_search_result_layout);
        cancalText = (TextView) parentView.findViewById(R.id.tv_option);
        cancalText.setOnClickListener(this);
        edt_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 0) {
                    ll_hot_word_layout.setVisibility(View.VISIBLE);
                    ll_search_result_layout.setVisibility(View.GONE);
                } else {
                    ll_hot_word_layout.setVisibility(View.GONE);
                    getFundNewSearch();
                }
            }
        });
    }

    /**
     * 初始化热搜词
     */
    @SuppressWarnings("unchecked")
    private void initHotWordData() {
        tag_flow.setMargin(10, 0, 5, 15);
        // 必须在设置adapter之前设置监听
        tag_flow.setOnFlowItemClickListener(new CustomFlowLayout.OnFlowItemClickListener() {
            @Override
            public void onItemClick(int position, View view) {
                Log.i("position", "position = " + position);
                edt_search.setText(searchData[position]);
                getFundNewSearch();
                ll_hot_word_layout.setVisibility(View.GONE);
                ll_search_result_layout.setVisibility(View.VISIBLE);
            }
        });
        tag_flow.setAdapter(new CustomFlowAdapter(Arrays.asList(searchData)) {
            @Override
            public View getView(CustomFlowLayout parent, int position, Object o) {
                TextView tvTag = (TextView) LayoutInflater.from(mContext).inflate(R.layout.view_hot_search_tag, parent, false);
                tvTag.setText((String) o);
                return tvTag;
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_option:
                dismiss();
                break;
        }
    }

    @Override
    public void onLoadMore() {
        page++;
        isLoadMore = true;
        getFundNewSearch();
    }
}
